<?php

namespace app\common\model;

use app\common\model\Coupon;
use app\common\model\BaseModel;


class CouponLog extends BaseModel
{

    

    

    // 表名
    protected $name = 'coupon_log';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'expire_time_text',
        'use_time_text',
        'create_time_text',
        'is_expired'
    ];
    

    



    public function getExpireTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['expire_time']) ? $data['expire_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getUseTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['use_time']) ? $data['use_time'] : '');
        return is_numeric($value)&&$value ? date("Y-m-d H:i:s", $value) : '';
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getIsExpiredAttr($value, $data)
    {
        return $data['expire_time']?$data['expire_time']>time()?0:1:1;
    }

    protected function setExpireTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUseTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function coupon()
    {
        return $this->belongsTo('Coupon', 'coupon_id', 'id')->joinType('LEFT');
    }
    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id')->joinType('LEFT');
    }
    public function invitee()
    {
        return $this->belongsTo('User', 'invitee_id', 'id')->joinType('LEFT');
    }

    /**
     * 注册发放优惠券
     */
    public function addRegisterCoupon($user_id){
        $list=Coupon::where(['status'=>'normal','type'=>0])->select()?:[];

        $data=[];
        foreach ($list as $l){
            $data[]=[
                'coupon_id'=>$l['id'],
                'user_id'=>$user_id,
                'create_time'=>time(),
                'use_time'=>0,
                'expire_time'=>time()+$l['valid_time']*86400
            ];
        }
        if($data)
            self::insertAll($data);
    }
}
